package com.syc.test;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.syc.test.entity.GjhExcelModel;
import com.syc.test.translate.TranslateUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.xwpf.usermodel.*;
import org.jsoup.Jsoup;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import sun.security.krb5.internal.PAData;

import java.io.*;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Description:
 * @CreateDate: 2025-04-10
 * @Version: 1.0.0
 * @menu
 */
public class FileTest02 {


    public static void main(String[] args)throws Exception {
        Map<String, Integer> siteSortRule = siteSortRule();
        List<GjhExcelModel> oneRecords = getExcelData();
        List<GjhExcelModel> twoRecords = new ArrayList<>();//getExcelData2();
        editTemplate(oneRecords,twoRecords,siteSortRule);

    }

    public static Map<String, Integer> siteSortRule(){
        Map<String, Integer> data=new HashMap<>();
        String filePath="E:\\temps\\广交会需求\\信源排序（补）.xlsx";
        try (FileInputStream fileInputStream=new FileInputStream(filePath)){
            List<String> excelData = ExcelUtils.read(fileInputStream, String.class, null);
            excelData.removeIf(site->StrUtil.isBlank(site));
            for (int i = 0; i < excelData.size(); i++) {
                String site = excelData.get(i);
                if (site.contains("（")) {
                    String mainSite = site.substring(0, site.indexOf("（")).trim();
                    String alternativeSite = site.substring(site.indexOf("（") + 1, site.indexOf("）")).trim();
                    data.put(mainSite, i);
                    data.put(alternativeSite, i);
                } else {
                    data.put(site, i);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return data;

    }


    public static List<GjhExcelModel> getExcelData2(){
        List<GjhExcelModel> data=new ArrayList<>();
        String filePath="E:\\temps\\广交会需求\\境外模版定稿.xlsx";
        Map<Integer,String> mapping=new HashMap<>();
        mapping.put(6,"title");
        mapping.put(7,"transTitle");
        mapping.put(8,"link");
        mapping.put(4,"site");
        mapping.put(10,"date");
        mapping.put(1,"author");
        mapping.put(12,"content");
        mapping.put(13,"transContent");
        try {
            FileInputStream fileInputStream=new FileInputStream(filePath);
            List<String> sheetNames = ExcelUtils.getSheetNames(fileInputStream);
            if(CollUtil.isEmpty(sheetNames)){
                return data;
            }
            sheetNames.removeIf(name->"境外负面".equals(name));
            for (String sheetName : sheetNames) {
                fileInputStream=new FileInputStream(filePath);
                List<GjhExcelModel> modelList = ExcelUtils.read(fileInputStream, GjhExcelModel.class, mapping, new String[]{sheetName});
                if(CollUtil.isNotEmpty(modelList)){
                    for (GjhExcelModel model : modelList) {
                        if(sheetName.equals("境外传统媒体")){
                            model.setTwoTitle(String.format("[%s]", sheetName));
                        }else {
                            model.setTwoTitle(String.format("[境外社交媒体]-%s", sheetName));
                        }
                    }
                    data.addAll(modelList);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return data;
    }

    public static List<GjhExcelModel> getExcelData(){
        List<GjhExcelModel> data=new ArrayList<>();
        String filePath="E:\\temps\\广交会需求\\广交会第4期 模板(1).xlsx";
        Map<Integer,String> mapping=new HashMap<>();
        mapping.put(1,"title");
        mapping.put(2,"link");
        mapping.put(3,"site");
        mapping.put(4,"date");
        mapping.put(6,"author");
        mapping.put(8,"digest");
        mapping.put(9,"content");
        mapping.put(12,"twoTitle");
        try (FileInputStream fileInputStream=new FileInputStream(filePath)){
            data = ExcelUtils.read(fileInputStream, GjhExcelModel.class, mapping);
            data.removeIf(item-> JSON.parseObject(JSON.toJSONString(item)).isEmpty());
            for (GjhExcelModel item : data) {
                if(StrUtil.isNotEmpty(item.getContent())){
                    item.setContent(Jsoup.parse(item.getContent()).text());
                }
                if(StrUtil.isNotEmpty(item.getTitle())){
                    item.setTitle(Jsoup.parse(item.getTitle()).text());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return data;
    }

    public static void editTemplate(List<GjhExcelModel> oneRecords,List<GjhExcelModel> twoRecords,Map<String, Integer> siteSortRule){
        String oneTitle="一、境内媒体涉外贸中心及其他相关报道内容",twoTitle="二、境外媒体涉广交会及家博会相关报道内容";
        for (GjhExcelModel oneRecord : oneRecords) {
            if(StrUtil.isEmpty(oneRecord.getContent())){
                oneRecord.setContent(analysisUrlContent(oneRecord.getLink()));
                if(StrUtil.isEmpty(oneRecord.getContent())){
                    oneRecord.setContent(oneRecord.getDigest());
                }
            }
        }
        for (GjhExcelModel twoRecord : twoRecords) {
            if(StrUtil.isNotEmpty(twoRecord.getAuthor()) && !twoRecord.getAuthor().equals("无") && StrUtil.isBlank(twoRecord.getTransAuthor())){
                twoRecord.setTransAuthor(TranslateUtil.execute(twoRecord.getAuthor()));
            }
            if(StrUtil.isNotEmpty(twoRecord.getTitle()) && StrUtil.isBlank(twoRecord.getTransTitle())){
                twoRecord.setTransTitle(TranslateUtil.execute(twoRecord.getTitle()));
            }
            if(StrUtil.isNotEmpty(twoRecord.getContent()) && StrUtil.isBlank(twoRecord.getTransContent())){
                twoRecord.setTransContent(TranslateUtil.execute(twoRecord.getContent()));
            }
        }
        sortRecords(oneRecords,siteSortRule);
        sortRecords(twoRecords,siteSortRule);
        Map<String, List<GjhExcelModel>> oneData = oneRecords.stream().collect(Collectors.groupingBy(GjhExcelModel::getTwoTitle));
        Map<String, List<GjhExcelModel>> twoData = twoRecords.stream().collect(Collectors.groupingBy(GjhExcelModel::getTwoTitle));
        String templateFilePath="E:\\temps\\广交会需求\\模板新.docx";
        String outputFilePath="E:\\temps\\广交会需求\\data.docx";
        List<String> titleSort=Arrays.asList("[广交会动态]","[经贸形势]","[自办展动态]","[展馆客展及活动]","[会展行业动态]","[海外参展办展]","[跨境电商平台]","[跨境支付]","[跨境电商综试区]","[敏感舆情信息]","[境外传统媒体]","[境外社交媒体]-官方账号","[境外社交媒体]-主流媒体","[境外商业账号及境外网民关注广交会]--境外商业账号","[境外商业账号及境外网民关注广交会]--境外网民");
        List<String> mediaTitles=Arrays.asList("[敏感舆情信息]","[境外社交媒体]-官方账号","[境外社交媒体]-主流媒体","[境外商业账号及境外网民关注广交会]--境外商业账号","[境外商业账号及境外网民关注广交会]--境外网民");
        Map<String,String> replaceFiled=new HashMap<>();
        replaceFiled.put("firstdate1","2025年第59期");
        try {
            XWPFDocument document = new XWPFDocument(new FileInputStream(templateFilePath));
            //替换模板
            Iterator<XWPFParagraph> iterator = document.getParagraphsIterator();
            while(iterator.hasNext()){
                XWPFParagraph paragraph = iterator.next();
                List<XWPFRun> runs = paragraph.getRuns();
                for (int i = 0; i < runs.size(); i++) {
                    XWPFRun xwpfRun = runs.get(i);
                    String text = xwpfRun.getText(xwpfRun.getTextPosition());
                    if(StrUtil.isNotEmpty(text)){
                        for (Map.Entry<String, String> entry : replaceFiled.entrySet()) {
                            text=text.replace(entry.getKey(),entry.getValue());
                        }
                        xwpfRun.setText(text,0);
                    }
                }
            }
            nextPage(document);
            createTitleParagraph(getParagraph(document,null,210,340,330,null,STLineSpacingRule.AUTO),
                    ParagraphAlignment.BOTH,0,oneTitle,true,null,16,"宋体");
            for (String ts : titleSort) {
                if(oneData.containsKey(ts)){
                    List<GjhExcelModel> models = oneData.get(ts);
                    createTitleParagraph(getParagraph(document,null,210,150,150,null,STLineSpacingRule.AUTO),
                            ParagraphAlignment.LEFT,1,ts,false,null,11,"Times New Roman");
                    if(mediaTitles.contains(ts)){
                        //敏感格式
                        createTitleParagraph(getParagraph(document,null,-57,260,260,null,STLineSpacingRule.AUTO),
                                ParagraphAlignment.CENTER,2,"涉广交会及广交会展馆负面信息",true,null,16,"宋体");
                        for (int i = 0; i < models.size(); i++) {
                            GjhExcelModel model = models.get(i);
                            String content1= String.format("%s用户@%s", model.getSite(),model.getAuthor());
                            DateTime dateTime = DateUtil.parse(model.getDate() + ":00");
                            String dateStr = DateUtil.format(dateTime, "MM月dd日");
                            String content2= String.format("%s发帖称，%s", dateStr,model.getContent());
                            XWPFParagraph contentP = document.createParagraph();
                            createTextParagraph(contentP, true, ParagraphAlignment.LEFT, content1, true, null, 11, "宋体 (正文)");
                            XWPFRun xwpfRun = contentP.createRun();
                            xwpfRun.setText(content2);
                            xwpfRun.setBold(false);
                            xwpfRun.setFontSize(11);
                            xwpfRun.setFontFamily("宋体");
                            createLink(document,model.getLink(),model.getLink(),11,"Times New Roman").addCarriageReturn();
                            if(i==models.size()-1){
                                nextPage(document);
                            }
                        }
                    }else {
                        for (int i = 0; i < models.size(); i++) {
                            GjhExcelModel model = models.get(i);
                            String title=(i+1)+"."+model.getSite()+"："+model.getTitle();
                            createTitleParagraph(getParagraph(document,null,-57,260,260,null,STLineSpacingRule.AUTO),
                                    ParagraphAlignment.CENTER,2,title,true,null,16,"宋体");
                            createTextParagraph(document.createParagraph(),false,ParagraphAlignment.CENTER,DateUtil.formatDate(DateUtil.parseDate(model.getDate())),false,null,11,"Times New Roman").addCarriageReturn();
                            createTextParagraph(document.createParagraph(), true, ParagraphAlignment.LEFT, model.getContent(), false, null, 11, "宋体");
                            createLink(document,model.getLink(),model.getLink(),11,"Times New Roman").addCarriageReturn();
                            nextPage(document);
                        }
                    }
                }
            }
            createTitleParagraph(getParagraph(document,null,210,340,330,null,STLineSpacingRule.AUTO),
                    ParagraphAlignment.BOTH,0,twoTitle,true,null,16,"宋体");
            boolean flag=false;
            for (String ts : titleSort) {
                if(twoData.containsKey(ts)){
                    List<GjhExcelModel> models = twoData.get(ts);
                    if(mediaTitles.contains(ts)){
                        if(!flag){
                            createTitleParagraph(getParagraph(document,null,210,150,150,null,STLineSpacingRule.AUTO),
                                    ParagraphAlignment.LEFT,1,"[境外社交媒体]",false,null,11,"Times New Roman");
                            flag=true;
                        }
                        createTitleParagraph(getParagraph(document,null,210,260,260,null,STLineSpacingRule.AUTO),
                                ParagraphAlignment.LEFT,2,ts,true,null,11,"Times New Roman");
                        for (int i = 0; i < models.size(); i++) {
                            GjhExcelModel model = models.get(i);
                            String content1= String.format("%s%s用户@%s",model.getTransAuthor(), model.getSite(),model.getAuthor());
                            DateTime dateTime = DateUtil.parse(model.getDate());
                            String dateStr = DateUtil.format(dateTime, "M月d日");
                            String content2= String.format("%s发帖称，%s", dateStr,model.getTransContent());
                            XWPFParagraph contentP = document.createParagraph();
                            createTextParagraph(contentP, true, ParagraphAlignment.LEFT, content1, true, null, 11, "宋体 (正文)");
                            XWPFRun xwpfRun = contentP.createRun();
                            xwpfRun.setText(content2);
                            xwpfRun.setBold(false);
                            xwpfRun.setFontSize(11);
                            xwpfRun.setFontFamily("宋体");
                            createLink(document,model.getLink(),model.getLink(),11,"Times New Roman");
                            createTextParagraph(document.createParagraph(), true, ParagraphAlignment.LEFT, "【原文】", false, null, 11, "宋体");
                            createTextParagraph(document.createParagraph(), true, ParagraphAlignment.LEFT, model.getContent(), false, null, 11, "宋体");
                            if(i==models.size()-1){
                                nextPage(document);
                            }
                        }
                    }else {
                        createTitleParagraph(getParagraph(document,null,210,150,150,null,STLineSpacingRule.AUTO),
                                ParagraphAlignment.LEFT,1,ts,false,null,11,"Times New Roman");
                        for (int i = 0; i < models.size(); i++) {
                            GjhExcelModel model = models.get(i);
                            String title=(i+1)+"."+model.getSite()+"："+model.getTransTitle();
                            createTitleParagraph(getParagraph(document,null,-57,260,260,null,STLineSpacingRule.AUTO),
                                    ParagraphAlignment.CENTER,2,title,true,null,16,"宋体");
                            createTextParagraph(document.createParagraph(),false,ParagraphAlignment.CENTER,DateUtil.formatDate(DateUtil.parseDate(model.getDate())),false,null,11,"Times New Roman").addCarriageReturn();
                            createTextParagraph(document.createParagraph(), true, ParagraphAlignment.LEFT, model.getTransContent(), false, null, 11, "宋体");
                            createLink(document,model.getLink(),model.getLink(),11,"Times New Roman");
                            createTextParagraph(document.createParagraph(), true, ParagraphAlignment.LEFT, "【原文】", false, null, 11, "宋体");
                            createTextParagraph(document.createParagraph(), true, ParagraphAlignment.LEFT, model.getContent(), false, null, 11, "宋体");
                            nextPage(document);
                        }
                    }
                }
            }
            //输出报告
            FileOutputStream outputStream = new FileOutputStream(outputFilePath);
            document.write(outputStream);
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static void sortRecords(List<GjhExcelModel> oneRecords, Map<String, Integer> siteSortRule) {
        oneRecords.sort((item1, item2) -> {
            int index1 = getIndexForSite(item1.getSite(), siteSortRule);
            int index2 = getIndexForSite(item2.getSite(), siteSortRule);
            if (index1 == -1) {
                index1 = Integer.MAX_VALUE;
            }
            if (index2 == -1) {
                index2 = Integer.MAX_VALUE;
            }
            if (index1 != index2) {
                return Integer.compare(index1, index2);
            }
            return 0;
        });
    }

    private static int getIndexForSite(String site, Map<String, Integer> siteToIndexMap) {
        if (site == null || site.isEmpty()) {
            return -1; // site 为空时不匹配
        }
        return siteToIndexMap.getOrDefault(site, -1); // 返回索引，未匹配返回 -1
    }

    public static String analysisUrlContent(String url){
        if(true){
            return null;
        }
        if(StrUtil.isEmpty(url) || !url.startsWith("http")){
            return null;
        }
        String resStr=null;
        try {
            JSONObject param=new JSONObject();
            param.put("url",url);
            HttpRequest post = HttpUtil.createPost("https://c.izhonghong.com/kys/artificialArt/analysisUrl");
            post.body(param.toJSONString(), ContentType.JSON.getValue());
            HttpResponse httpResponse = post.execute();
            resStr=httpResponse.body();
            String text=JSON.parseObject(resStr).getJSONObject("data").getString("text").trim();
            text=text.replaceAll("(\\n(\\s|\\n)|\\n)+","&br;");
            text=text.replaceAll("<[^>]+>","");
            return text;
        }catch (Exception e){
//            e.printStackTrace();
        }
        return null;
    }

    private static XWPFParagraph nextPage(XWPFDocument document){
        // 插入分页符
        XWPFParagraph pageBreak = document.createParagraph();
        CTP ctp = pageBreak.getCTP();
        ctp.addNewPPr().addNewPageBreakBefore();
        return pageBreak;
    }

    private static XWPFParagraph getParagraph(XWPFDocument document, Integer left, Integer right, Integer befor, Integer after, Integer line, STLineSpacingRule.Enum rule) {
        XWPFParagraph paragraph = document.createParagraph();
        if(left!=null || right!=null){
            //设置缩进
            CTPPr ppr = paragraph.getCTP().isSetPPr() ? paragraph.getCTP().getPPr() : paragraph.getCTP().addNewPPr();
            CTOnOff ctOnOff = ppr.isSetAdjustRightInd() ? ppr.getAdjustRightInd() : ppr.addNewAdjustRightInd();
            ctOnOff.setVal(STOnOff.OFF);//关闭自动右缩进
            CTInd ind = ppr.isSetInd() ? ppr.getInd() : ppr.addNewInd();
            if(left!=null){
                ind.setLeft(BigInteger.valueOf(left));
            }
            if(right!=null){
                ind.setRight(BigInteger.valueOf(right));
            }
        }
        if(befor!=null && after!=null){
            //设置间距段前，段后
            CTPPr ppr = paragraph.getCTP().isSetPPr() ? paragraph.getCTP().getPPr() : paragraph.getCTP().addNewPPr();
            CTOnOff ctOnOff = ppr.isSetSnapToGrid() ? ppr.getSnapToGrid() : ppr.addNewSnapToGrid();
            ctOnOff.setVal(STOnOff.OFF);//关闭自动网格对齐
            CTSpacing spacing = ppr.isSetSpacing() ? ppr.getSpacing() : ppr.addNewSpacing();
            if(befor!=null){
                spacing.setBefore(BigInteger.valueOf(befor));
            }
            if(after!=null){
                spacing.setAfter(BigInteger.valueOf(after));
            }
        }
        if(line!=null || rule!=null){
            //设置行距
            CTPPr ppr = paragraph.getCTP().isSetPPr() ? paragraph.getCTP().getPPr() : paragraph.getCTP().addNewPPr();
            CTSpacing spacing = ppr.isSetSpacing() ? ppr.getSpacing() : ppr.addNewSpacing();
            if(rule!=null){
                spacing.setLineRule(rule);
            }
            if(line!=null){
                spacing.setLine(BigInteger.valueOf(line));
            }
        }
        return paragraph;
    }

    /**
     * 创建标题段落
     * @param paragraphAlignment 文本对齐方式
     * @param titleNum 标题级别 1-9
     * @param text 文本
     * @param bold 是否加粗
     * @param color 字体颜色
     * @param fontSize 字体大小
     * @param fontFamily 字体名称
     * @return
     */
    public static XWPFRun createTitleParagraph(XWPFParagraph paragraph, ParagraphAlignment paragraphAlignment, int titleNum, String text, boolean bold, String color, int fontSize, String fontFamily) {
        paragraph.setAlignment(paragraphAlignment);
        CTDecimalNumber ctDecimalNumber = CTDecimalNumber.Factory.newInstance();
        ctDecimalNumber.setVal(BigInteger.valueOf(titleNum));
        paragraph.getCTP().getPPr().setOutlineLvl(ctDecimalNumber);
        XWPFRun xwpfRun = paragraph.createRun();
        xwpfRun.setText(text);
        xwpfRun.setBold(bold);
        if(color!=null){
            xwpfRun.setColor(color);
        }
        xwpfRun.setFontSize(fontSize);
        xwpfRun.setFontFamily(fontFamily);
        return xwpfRun;
    }

    /**
     * 创建内容段落
     * @param needIndentation 是否需要缩进
     * @param paragraphAlignment 文本对齐方式
     * @param text 文本
     * @param bold 是否加粗
     * @param color 字体颜色
     * @param fontSize 字体大小
     * @param fontFamily 字体名称
     * @return
     */
    public static XWPFRun createTextParagraph(XWPFParagraph paragraph,boolean needIndentation,ParagraphAlignment paragraphAlignment,String text,boolean bold,String color,int fontSize,String fontFamily) {
        XWPFRun xwpfRun=null;
        String[] lines = text.split("&br;");
        XWPFParagraph p=paragraph;
        for (int i = 0; i < lines.length; i++) {
            String line=lines[i].trim();
            if(StrUtil.isBlank(line)){
                continue;
            }
            if(p==null){
                p=paragraph.getDocument().createParagraph();
            }
            p.setAlignment(paragraphAlignment);
            xwpfRun = p.createRun();
            line=line.replaceAll("^(\\s|\\u00A0|\\u3000)+","");
            xwpfRun.setText(line);
            xwpfRun.setBold(bold);
            if(color!=null){
                xwpfRun.setColor(color);
            }
            xwpfRun.setFontSize(fontSize);
            xwpfRun.setFontFamily(fontFamily);
            if(needIndentation){
                // 设置段落缩进
                p.setIndentationFirstLine(480);
            }
            p=null;
        }
        return xwpfRun;
    }

    public static XWPFHyperlinkRun createLink(XWPFDocument document, String url, String urlDesc, int fontSize, String fontFamily){
        XWPFParagraph paragraph = document.createParagraph();
        String rId = paragraph.getDocument().getPackagePart().addExternalRelationship(
                url,
                XWPFRelation.HYPERLINK.getRelation()
        ).getId();
        CTHyperlink cthyperLink=paragraph.getCTP().addNewHyperlink();
        cthyperLink.setId(rId);
        cthyperLink.addNewR();
        XWPFHyperlinkRun hyperlinkrun = new XWPFHyperlinkRun(
                cthyperLink,
                cthyperLink.getRArray(0),
                paragraph
        );
        hyperlinkrun.setText(urlDesc);
        hyperlinkrun.setColor("1C30EC");
        hyperlinkrun.setFontSize(fontSize);
        hyperlinkrun.setFontFamily(fontFamily);
        hyperlinkrun.setUnderline(UnderlinePatterns.SINGLE);
        // 设置首行缩进（单位：缇）
        paragraph.setIndentationFirstLine(480);
        return hyperlinkrun;
    }

    private static void addDynamicTocEntry(XWPFParagraph paragraph, boolean bold,String title, int pageNumber) {
        /*int totalWidth = 85;
        int dotsCount = Math.max(totalWidth - title.length() - String.valueOf(pageNumber).length(), 3); // 至少保留 3 个点
        StringBuilder dotBuilder=new StringBuilder();
        for (int i = 0; i < dotsCount; i++) {
            dotBuilder.append(".");
        }
        String dots = dotBuilder.toString();*/
        String tocEntry = title + "  " + pageNumber;
        XWPFRun run = paragraph.createRun();
        run.setText(tocEntry);
        run.setBold(bold);
        run.addCarriageReturn();
    }

    private static void addSettingsToDocx(Path inputDocxPath, String outputDocxPath) throws IOException, InvalidFormatException {
        // 创建 settings.xml 内容
        String settingsXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                "<w:settings xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">\n" +
                "    <w:docGrid w:type=\"lines\" w:linePitch=\"240\"/>\n" +
                "    <w:autoSpaceDE w:val=\"off\"/>\n" +
                "    <w:autoSpaceDN w:val=\"off\"/>\n" +
                "</w:settings>";

        // 打开输入的 .docx 文件并复制内容到输出文件
        try (OPCPackage pkg = OPCPackage.open(inputDocxPath.toFile());
             ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outputDocxPath))) {

            boolean settingsAdded = false; // 标记是否已添加 settings.xml

            // 遍历现有的条目并复制
            for (PackagePart part : pkg.getParts()) {
                String partName = part.getPartName().toString();

                // 跳过 PackagePropertiesPart 类型的部分
                if (partName.startsWith("/docProps/")) {
                    continue; // 忽略文档属性部分
                }

                // 检查是否需要跳过原有的 settings.xml
                if (partName.equals("/word/settings.xml")) {
                    settingsAdded = true; // 标记已存在 settings.xml
                    continue; // 跳过原有 settings.xml
                }

                // 复制其他部分
                zos.putNextEntry(new ZipEntry(partName.substring(1))); // 去掉开头的斜杠
                zos.write(readAllBytes(part.getInputStream())); // 使用自定义方法读取字节流
                zos.closeEntry();
            }

            // 如果没有 settings.xml，则添加新的 settings.xml
            if (!settingsAdded) {
                zos.putNextEntry(new ZipEntry("word/settings.xml"));
                zos.write(settingsXml.getBytes());
                zos.closeEntry();
            }
        }
    }

    private static byte[] readAllBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[1024]; // 每次读取 1KB 数据

        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }

        buffer.flush();
        return buffer.toByteArray();
    }




}
